package cn.zhuizikejithreeig.com.passenger;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import cn.zhuizikejithreeig.com.brodcat.NetBroadcastReceiver;
import cn.zhuizikejithreeig.com.brodcat.NetUtil;
import cn.zhuizikejithreeig.com.brodcat.PrensentView;
import cn.zhuizikejithreeig.com.utils.AppManager;

abstract public class BasicActivity extends AppCompatActivity implements PrensentView {

    private ImageView mHuaWei;
    private LinearLayout mHandLinear;
    private LinearLayout mContentLayout;
    private RelativeLayout mLeft;
    private RelativeLayout mRight;
    private TextView mTitle;
    private LinearLayout mHandRealat;
    private LinearLayout mSlietBar;
    private ProgressDialog mDialog;
    private RelativeLayout mRelatLeft;
    private RelativeLayout mRelatRight;
    private TextView mRelatTitle;
    private static final int MY_SINGLE = 100;
    private static final int MY_PERMISIONLIST = 101;
    /**
     * 网络类型
     */
    private int netMobile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //        入侵式状态栏，只有5.0以后才能用，并且只能加到R.layout.xxx前面
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            //这句话是添加底部导航栏的颜色(华为手机默认是透明色)
            window.setNavigationBarColor(getResources().getColor(R.color.black));
        }


        ButterKnife.bind(BasicActivity.this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic);


        mHuaWei = (ImageView) findViewById(R.id.huawei);
        mHandLinear = (LinearLayout) findViewById(R.id.handlinear);
        mHandRealat = (LinearLayout) findViewById(R.id.handrealat);
        mContentLayout = (LinearLayout) findViewById(R.id.content_layout);
        mSlietBar = (LinearLayout) findViewById(R.id.slietbar);

        //求出hand标题里面的内容
        mLeft = (RelativeLayout) findViewById(R.id.left);
        mRight = (RelativeLayout) findViewById(R.id.right);
        mTitle = (TextView) findViewById(R.id.titletext);

        //相对布局的显示,注意两个不能合并到一起,不然文字和图标不会正常显示
        mRelatLeft = (RelativeLayout) findViewById(R.id.relatleft);
        mRelatRight = (RelativeLayout) findViewById(R.id.relatright);
        mRelatTitle = (TextView) findViewById(R.id.relattitletext);

        //添加公共的进度条
        mDialog = new ProgressDialog(BasicActivity.this);
        //设置进度条不可取消
        mDialog.setCancelable(false);

        //根据底部是否含有黑色框来控制显示黑色框的颜色
        if (navigationBarExist(BasicActivity.this)) {
            mHuaWei.setVisibility(View.VISIBLE);
        } else {
            mHuaWei.setVisibility(View.GONE);
        }

        //初始化判断有没有网络
        inspectNet();
        //初始化操作
        init();

        AppManager.getInstance().addActivity(this); //添加到栈中
    }

    private void init() {

        // 获得inflater
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // 把继承该BaseAcitivyt的layoutID放进来 显示

        View view = inflater.inflate(setContView(), null);
        // content_layout.addView(view);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        // content_layout.addView(view, layoutParams);
        view.setLayoutParams(layoutParams);
        if (null != mContentLayout) {
            mContentLayout.addView(view);
        }

        switch (setHandIndexShow()) {
            //不显示头布局
            case 0:
                mHandLinear.setVisibility(View.GONE);
                mHandRealat.setVisibility(View.GONE);
                break;
            //设置线性排布标题
            case 1:
                mHandLinear.setVisibility(View.VISIBLE);
                mHandRealat.setVisibility(View.GONE);
                break;
            //设置相对排布标题
            case 2:
                mHandLinear.setVisibility(View.GONE);
                mHandRealat.setVisibility(View.VISIBLE);
                break;
            case 3:
                mHandLinear.setVisibility(View.GONE);
                mHandRealat.setVisibility(View.GONE);
                break;
        }


        if (actionBarNeedGoon()) {
            mSlietBar.setVisibility(View.GONE);
        }
        ;


        initView();
        initToDo();
    }

    /**
     * @return 返回上标题是否需要隐藏
     */
    protected abstract boolean actionBarNeedGoon();


    //该方法是判断,有没有底部导航栏的
    public static boolean navigationBarExist(Activity activity) {
        WindowManager windowManager = activity.getWindowManager();
        Display d = windowManager.getDefaultDisplay();

        DisplayMetrics realDisplayMetrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            d.getRealMetrics(realDisplayMetrics);
        }
        int realHeight = realDisplayMetrics.heightPixels;
        int realWidth = realDisplayMetrics.widthPixels;
        DisplayMetrics displayMetrics = new DisplayMetrics();
        d.getMetrics(displayMetrics);
        int displayHeight = displayMetrics.heightPixels;
        int displayWidth = displayMetrics.widthPixels;
        return (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;
    }


    /**
     * @return 返回布局
     */
    public abstract int setContView();

    /**
     * @return 返回头部是否显示，以及怎么显示
     * <p>
     * 1.都不显示
     * 2.线性排布标题
     * 3.相对排布标题
     */
    protected abstract int setHandIndexShow();

    /**
     * 设置 Title的文字，传一个resID，如：R.string.home_title setTitle_V(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     *
     * @throws
     * @since 1.0.0
     */

    public void setTitle(String msg) {
        mTitle.setText(msg);
        mRelatTitle.setText(msg);
    }

    /**
     * 设置左边按钮里是文字 setLeftShow(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @throws
     * @since 1.0.0
     */
    public void setLeftShow(int tag, int resID, String name) {
        if (null == mLeft) {
            return;
        }
        mLeft.removeAllViews();
        mLeft.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mLeft.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            mLeft.addView(view, params);
        } else if (tag == 3) {
            View view = getLayoutInflater().inflate(R.layout.selft, null);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            TextView liftText = (TextView) view.findViewById(R.id.lifttext);
            liftText.setText(name);
            mLeft.addView(view, params);
        }
    }

    /**
     * 设置左边按钮里是文字 setLeftShow(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @throws
     * @since 1.0.0
     */
    public void setRelatLeftShow(int tag, int resID, String name) {
        if (null == mRelatLeft) {
            return;
        }
        mRelatLeft.removeAllViews();
        mRelatLeft.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRelatLeft.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            mRelatLeft.addView(view, params);
        } else if (tag == 3) {
            View view = getLayoutInflater().inflate(R.layout.selft, null);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            TextView liftText = (TextView) view.findViewById(R.id.lifttext);
            liftText.setText(name);
            mRelatLeft.addView(view, params);
        }
    }


    /**
     * 设置右边边按钮里是文字 setRightShow(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @throws
     * @since 1.0.0
     */
    public void setRightShow(int tag, int resID) {
        if (null == mRight) {
            return;
        }
        mRight.removeAllViews();
        mRight.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRight.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRight.addView(view, params);
        }
    }


    /**
     * 设置右边边按钮里是文字 setRightShow(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @throws
     * @since 1.0.0
     */
    public void setRelatRightShow(int tag, int resID) {
        if (null == mRelatRight) {
            return;
        }
        mRelatRight.removeAllViews();
        mRelatRight.setVisibility(View.VISIBLE);
        if (tag == 0) {
            View view = getLayoutInflater().inflate(R.layout.textview, null);
            TextView text = view.findViewById(R.id.text);
            text.setText(this.getResources().getString(resID));
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRelatRight.addView(view, params);
        } else if (tag == 1) {
            View view = getLayoutInflater().inflate(R.layout.imageview, null);
            ImageView imageView = view.findViewById(R.id.icon);
            imageView.setImageResource(resID);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mRelatRight.addView(view, params);
        }
    }

    /**
     * 获取 left , 左边按钮 getLift_V(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @return RelativeLayout
     * @throws
     * @since 1.0.0
     */
    public RelativeLayout getLift() {
        if (mLeft == null) {
            mLeft = findViewById(R.id.left);
            return mLeft;
        }
        return mLeft;
    }

    /**
     * 获取 right , 右边按钮 getRight_V(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @return RelativeLayout
     * @throws
     * @since 1.0.0
     */
    public RelativeLayout getRight() {
        if (mRight == null) {
            mRight = findViewById(R.id.right);
            return mRight;
        }
        return mRight;
    }

    /**
     * 获取 left , 左边按钮 getLift_V(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @return RelativeLayout
     * @throws
     * @since 1.0.0
     */
    public RelativeLayout getRelatLift() {
        if (mRelatLeft == null) {
            mRelatLeft = findViewById(R.id.relatleft);
            return mRelatLeft;
        }
        return mRelatLeft;
    }

    /**
     * 获取 right , 右边按钮 getRight_V(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @return RelativeLayout
     * @throws
     * @since 1.0.0
     */
    public RelativeLayout getRelatRight() {
        if (mRelatRight == null) {
            mRelatRight = findViewById(R.id.relatright);
            return mRelatRight;
        }
        return mRelatRight;
    }

    /**
     * 这是专门做跳转界面的在父类BasicActivity中
     *
     * @param clazz   要跳转的界面.class
     * @param isFinsh 是否要让这个界面从任务栈中去除
     */
    public void skipOtherActivity(Class clazz, boolean isFinsh) {

        startActivity(new Intent(BasicActivity.this, clazz));
        if (isFinsh) {
            finish();
        }
    }


    /**
     * 处理业务逻辑
     */
    protected abstract void initToDo();

    /**
     * 初始化view
     */
    protected abstract void initView();

    /**
     * @param permision 需要的单个权限
     */
    public void getSinglePermission(String permision) {
        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, permision) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{permision},
                        MY_SINGLE);
            }
        }
    }

    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    List<String> mPermissionList = new ArrayList<>();

    public void getListPermissions(String[] permissions) {
        mPermissionList.clear();
        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }
            if (!mPermissionList.isEmpty()) {
                //将List转为数组
                String[] permissionarrs = mPermissionList.toArray(new String[mPermissionList.size()]);
                ActivityCompat.requestPermissions(BasicActivity.this, permissionarrs, MY_PERMISIONLIST);

            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        //单项回调
        if (requestCode == MY_SINGLE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    showToast("权限已申请");
            } else {
//                    showToast("权限已拒绝");
                //判断是否勾选禁止后不再询问
                boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(BasicActivity.this, permissions[0]);
                if (!showRequestPermission) {
                    Intent intent = new Intent(
                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }
            }
        } else if (requestCode == MY_PERMISIONLIST) {

            for (int i = 0; i < grantResults.length; i++) {

                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(BasicActivity.this, permissions[i]);
                    if (showRequestPermission) {
                        Intent intent = new Intent(
                                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivity(intent);
                    }
                }
            }
        }
    }

    //监听网络。是那种网络

    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        isNetConnect();
        if (netMobile == 1) {
            System.out.println("inspectNet：连接wifi");
        } else if (netMobile == 0) {
            System.out.println("inspectNet:连接移动数据");
        } else if (netMobile == -1) {
            System.out.println("inspectNet:当前没有网络");

        }
        netChengedListen(netMobile);


    }

    protected abstract void netChengedListen(int netMobile);

    //监听是否有网
    private boolean inspectNet() {
        this.netMobile = NetUtil.getNetWorkState(BasicActivity.this);
        return isNetConnect();
    }

    /**
     * 判断有无网络 。
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect() {
        if (netMobile == 1) {
            return true;
        } else if (netMobile == 0) {
            return true;
        } else if (netMobile == -1) {
            return false;

        }
        return false;
    }
    private NetBroadcastReceiver netWorkStateReceiver;

    /**
     * 动态开启网络监听
     */
    public void startNetListen(){
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetBroadcastReceiver(BasicActivity.this);
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
        System.out.println("zhuce注册了");
    }

    /**
     * 销毁网络监听
     */
    public void onDesttroyNetListen(){
        if (netWorkStateReceiver!=null) {
            unregisterReceiver(netWorkStateReceiver);
            netWorkStateReceiver = null;
            System.out.println("zhuce销毁了");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getInstance().finishActivity(this); //从栈中移除
    }
}
